'use strict';
module.exports = {
	/**
	 * 点赞/取消、踩/取消点赞操作
	 * @url client/user/kh/praise 前端调用的url参数地址
	 * data 请求参数 说明
	 * @param {String} _id  ID
	 * @param {Number} status 1赞 2取消 3踩 4取消
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------
		let { _id, status } = data;
		
		let dbName = "db-praise";
		
		if(vk.pubfn.isNull(_id)) {
			return { code: -1, msg: "Invalid _id parameter"}
		}
		
		let dbRes = await vk.baseDao.findByWhereJson({
			dbName,
			whereJson: {
				article_id: _id,
				wx_openid: userInfo.wx_openid
			}
		})
		
		if(!vk.pubfn.isNull(dbRes)) {
			if(status !== 2 && status !== 4) {
				return { code: -1, msg: "Invalid status parameter"}
			}
			res["data"] = await vk.baseDao.deleteById({
				dbName,
				id: dbRes._id
			})
		} else {
			if(status !== 1 && status !== 3) {
				return { code: -1, msg: "Invalid status parameter"}
			}
			res["data"] = await vk.baseDao.add({
				dbName,
				dataJson: {
					article_id: _id,
					status: status,
					wx_openid: userInfo.wx_openid,
					uid: userInfo._id
				}
			})
		}
		
		delete res["data"];
		
		let dataJson = {};
		
		if(status === 1 || status === 2) {
			dataJson["praise_num"] = status !== 2? _.inc(1): _.inc(-1);
		} else {
			dataJson["deny_num"] = status !== 4? _.inc(1): _.inc(-1);
		}
		
		let num = await vk.baseDao.update({
			dbName: "db-article",
			whereJson: {
				_id: _id
			},
			dataJson
		})
		
		res["msg"] = status !== 2 && status !== 4? "操作成功": "取消成功";
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
